package com.jmag.nop.service.common.exception;

import com.jmag.nop.service.common.message.Error;
import com.jmag.nop.service.common.message.ErrorMeta;
import com.jmag.nop.service.common.message.ErrorFactory;

import java.util.Locale;

/**
 * @ClassName ApiException
 * @Description TODO
 * @Author JMAG
 * @Date 2020/5/12 8:24
 * @Version 1.0
 **/
public class ApiErrorException extends RuntimeException {
    private transient Error error;

    private transient ErrorMeta errorMeta;
    private transient Object[] params;

    public ApiErrorException(ErrorMeta errorMeta, Object... params) {
        this.errorMeta = errorMeta;
        this.params = params;
    }

    public ApiErrorException(Throwable cause, ErrorMeta errorMeta, Object... params) {
        super(cause);
        this.errorMeta = errorMeta;
        this.params = params;
    }

    public Error getError(Locale locale) {
        if (error == null) {
            error = ErrorFactory.getError(this.errorMeta, locale, params);
        }
        return error;
    }

    @Override
    public String getMessage() {
        String message = super.getMessage();
        return message == null ? errorMeta.toString() : message;
    }
}
